package com.origin.grid.framework.modules.identity;


import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UrlPathHelper;

import java.util.List;

/**
 * 身份认证
 */
@Component
@Slf4j
@ConfigurationProperties("identity")
public class IdentityInterception implements HandlerInterceptor {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private List<String> ignoredUrl;

    public List<String> getIgnoredUrl() {
        return ignoredUrl;
    }

    public void setIgnoredUrl(List<String> ignoredUrl) {
        this.ignoredUrl = ignoredUrl;
    }


    private boolean checkIdentity(String token, String tag) {

        String tagToken = tag + "_" + token;
        // 检查redis
        String tempToken = (String) redisTemplate.opsForValue().get(tagToken);
        log.info("保存的redis {}", tempToken);
        if (tempToken == null) {
            return false;
        }
        return true;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {


        String requestUrl = request.getRequestURL().toString();
        String token = request.getHeader("token");
        UrlPathHelper urlPathHelper = new UrlPathHelper();


        String path = urlPathHelper.getPathWithinApplication(request);

        log.info("请求地址 {} , 请求头 {} , 请求方法 {}", requestUrl, token, path);
        AntPathMatcher pathMatcher = new AntPathMatcher();

        for (String s : ignoredUrl) {
            boolean matches = pathMatcher.match(s, path);
            log.info("忽略的接口 {}  是否匹配  {}", s, matches);
            if (matches) {
                return true;
            }
        }
        System.out.println("进入拦截器了");

        String tag = "";

        if (pathMatcher.match("/admin-api/**", path)) {
            tag = "admin_api";
        } else if (pathMatcher.match("/app-api/**", path)) {
            tag = "app_api";
        }

        return true;
//        return checkIdentity("Yang", tag);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        //
        System.out.println("controller 执行完了");
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("我获取到了一个返回的结果：" + response);
        System.out.println("请求结束了");
    }
}
